<template>
  <div class="avatar-upload" :class="{ [`avatar-upload--${size}`]: size }">
    <!-- 头像显示区域 -->
    <div class="avatar-preview" @click="handleAvatarClick">
      <div class="avatar-image">
        <img
          v-if="currentAvatarUrl"
          :src="currentAvatarUrl"
          :alt="alt"
          @error="handleImageError"
        />
        <div v-else class="avatar-placeholder">
          <el-icon :size="placeholderIconSize">
            <Avatar />
          </el-icon>
        </div>
      </div>
      
      <!-- 编辑遮罩 -->
      <div v-if="editable" class="avatar-overlay">
        <el-icon :size="overlayIconSize">
          <Camera />
        </el-icon>
        <span class="overlay-text">更换头像</span>
      </div>
      
      <!-- 上传进度 -->
      <div v-if="uploading" class="upload-progress">
        <el-progress
          type="circle"
          :percentage="uploadProgress"
          :width="progressSize"
          :stroke-width="4"
        />
      </div>
    </div>
    
    <!-- 操作按钮 -->
    <div v-if="editable && showActions" class="avatar-actions">
      <el-button
        type="primary"
        size="small"
        :loading="uploading"
        @click="handleUploadClick"
      >
        <el-icon><Upload /></el-icon>
        上传头像
      </el-button>
      
      <el-button
        v-if="currentAvatarUrl && !isDefaultAvatar"
        type="danger"
        size="small"
        plain
        :loading="resetting"
        @click="handleResetAvatar"
      >
        <el-icon><RefreshLeft /></el-icon>
        重置默认
      </el-button>
    </div>
    
    <!-- 隐藏的文件选择器 -->
    <input
      ref="fileInputRef"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleFileSelect"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Avatar, Camera, Upload, RefreshLeft, Warning } from '@element-plus/icons-vue'
import { uploadUserAvatar, resetUserAvatar, buildAvatarUrl, validateAvatarFile } from '@/api/avatar'
import { useUserStore } from '@/stores/user'

const props = defineProps({
  // 用户ID
  userId: {
    type: [String, Number],
    default: null
  },
  // 头像URL
  avatarUrl: {
    type: String,
    default: ''
  },
  // 尺寸大小
  size: {
    type: String,
    default: 'medium', // mini, small, medium, large, extra-large
    validator: (value) => ['mini', 'small', 'medium', 'large', 'extra-large'].includes(value)
  },
  // 是否可编辑
  editable: {
    type: Boolean,
    default: true
  },
  // 是否显示操作按钮
  showActions: {
    type: Boolean,
    default: true
  },
  // alt文本
  alt: {
    type: String,
    default: '用户头像'
  },
  // 是否启用API功能（用于降级处理）
  enableApi: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['avatar-updated', 'upload-start', 'upload-success', 'upload-error'])

const userStore = useUserStore()

// 响应式数据
const fileInputRef = ref(null)
const currentAvatarUrl = ref('')
const uploading = ref(false)
const resetting = ref(false)
const uploadProgress = ref(0)

// 计算属性
const placeholderIconSize = computed(() => {
  const sizeMap = {
    mini: 20,
    small: 24,
    medium: 32,
    large: 40,
    'extra-large': 48
  }
  return sizeMap[props.size] || 32
})

const overlayIconSize = computed(() => {
  const sizeMap = {
    mini: 12,
    small: 14,
    medium: 16,
    large: 18,
    'extra-large': 20
  }
  return sizeMap[props.size] || 16
})

const progressSize = computed(() => {
  const sizeMap = {
    mini: 40,
    small: 50,
    medium: 60,
    large: 70,
    'extra-large': 80
  }
  return sizeMap[props.size] || 60
})

const isDefaultAvatar = computed(() => {
  return !currentAvatarUrl.value || 
         currentAvatarUrl.value.includes('default') ||
         currentAvatarUrl.value.includes('avatar.jpg')
})

// 初始化头像URL
const initAvatarUrl = () => {
  if (props.avatarUrl) {
    currentAvatarUrl.value = buildAvatarUrl(props.avatarUrl)
  } else if (userStore.userInfo?.avatar) {
    currentAvatarUrl.value = buildAvatarUrl(userStore.userInfo.avatar)
  } else {
    currentAvatarUrl.value = '/default-avatar.svg'
  }
}

// 监听props变化
watch(() => props.avatarUrl, initAvatarUrl, { immediate: true })

// 处理头像点击
const handleAvatarClick = () => {
  if (props.editable) {
    handleUploadClick()
  }
}

// 处理上传按钮点击
const handleUploadClick = () => {
  if (fileInputRef.value) {
    fileInputRef.value.click()
  }
}

// 处理文件选择
const handleFileSelect = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 验证文件
  const validation = validateAvatarFile(file)
  if (!validation.valid) {
    ElMessage.error(validation.message)
    return
  }
  
  // 直接上传文件
  await handleFileUpload(file)
}

// 处理文件上传
const handleFileUpload = async (file) => {
  try {
    uploading.value = true
    uploadProgress.value = 0
    emit('upload-start')
    
    // 创建FormData
    const formData = new FormData()
    formData.append('file', file)
    
    // 模拟上传进度
    const progressInterval = setInterval(() => {
      if (uploadProgress.value < 90) {
        uploadProgress.value += 10
      }
    }, 100)
    
    // 上传头像
    const response = await uploadUserAvatar(formData)
    
    clearInterval(progressInterval)
    uploadProgress.value = 100
    
    console.log('头像上传响应:', response)
    
    // 更新头像URL
    if (response.data && response.data.avatarUrl) {
      console.log('原始头像URL:', response.data.avatarUrl)
      const builtUrl = buildAvatarUrl(response.data.avatarUrl)
      console.log('构建后的头像URL:', builtUrl)
      
      currentAvatarUrl.value = builtUrl
      
      // 更新用户store
      if (userStore.userInfo) {
        userStore.userInfo.avatar = response.data.avatarUrl
        console.log('更新用户store头像:', response.data.avatarUrl)
      }
      
      // 更新用户store的当前头像
      userStore.updateUserAvatar(response.data.avatarUrl)
      
      ElMessage.success('头像上传成功')
      emit('upload-success', response.data)
      emit('avatar-updated', response.data.avatarUrl)
    } else {
      console.error('上传响应数据格式错误:', response)
      throw new Error('上传响应数据格式错误')
    }
    
  } catch (error) {
    console.error('头像上传失败:', error)
    
    // 根据不同错误类型给出不同提示
    let errorMessage = '头像上传失败'
    
    if (error.response?.status === 401) {
      errorMessage = '登录已过期，请重新登录'
      // 可能需要跳转到登录页
      userStore.logout()
    } else if (error.response?.status === 413) {
      errorMessage = '文件太大，请选择5MB以下的图片'
    } else if (error.response?.status === 415) {
      errorMessage = '不支持的文件格式'
    } else if (error.response?.status === 500) {
      errorMessage = '服务器错误，请稍后重试'
    } else if (error.message?.includes('timeout')) {
      errorMessage = '上传超时，请检查网络连接'
    } else if (error.message?.includes('Network Error')) {
      errorMessage = '网络连接失败，请检查网络'
    }
    
    ElMessage.error(errorMessage)
    emit('upload-error', error)
  } finally {
    uploading.value = false
    uploadProgress.value = 0
    
    // 清空文件选择器
    if (fileInputRef.value) {
      fileInputRef.value.value = ''
    }
  }
}

// 处理重置头像
const handleResetAvatar = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要重置为默认头像吗？',
      '确认重置',
      {
        type: 'warning'
      }
    )
    
    resetting.value = true
    
    const response = await resetUserAvatar()
    
    currentAvatarUrl.value = buildAvatarUrl(response.data.avatarUrl)
    
    // 更新用户store
    if (userStore.userInfo) {
      userStore.userInfo.avatar = response.data.avatarUrl
    }
    
    ElMessage.success('头像已重置为默认头像')
    emit('avatar-updated', response.data.avatarUrl)
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置头像失败:', error)
      ElMessage.error(error.message || '重置头像失败')
    }
  } finally {
    resetting.value = false
  }
}

// 处理图片加载错误
const handleImageError = () => {
  currentAvatarUrl.value = '/default-avatar.svg'
}
</script>

<style lang="scss" scoped>
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  
  // 不同尺寸的头像
  &--mini .avatar-preview {
    width: 32px;
    height: 32px;
  }
  
  &--small .avatar-preview {
    width: 48px;
    height: 48px;
  }
  
  &--medium .avatar-preview {
    width: 80px;
    height: 80px;
  }
  
  &--large .avatar-preview {
    width: 120px;
    height: 120px;
  }
  
  &--extra-large .avatar-preview {
    width: 160px;
    height: 160px;
  }
}

.avatar-preview {
  position: relative;
  width: 80px;
  height: 80px;
  cursor: pointer;
  
  .avatar-image {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    overflow: hidden;
    border: 3px solid $border-light;
    transition: $transition-fast;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  
  .avatar-placeholder {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background: $bg-gray;
    display: flex;
    align-items: center;
    justify-content: center;
    color: $text-gray;
    border: 2px dashed $border-gray;
  }
  
  .avatar-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: $text-white;
    opacity: 0;
    transition: $transition-fast;
    
    .overlay-text {
      font-size: 10px;
      margin-top: 2px;
    }
  }
  
  &:hover .avatar-overlay {
    opacity: 1;
  }
  
  &:hover .avatar-image {
    border-color: $primary-color;
  }
  
  .upload-progress {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

.avatar-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
  
  .api-disabled-tip {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    color: $text-gray;
    padding: 4px 8px;
    border-radius: $border-radius;
    background: $bg-light;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .avatar-actions {
    .el-button {
      font-size: 12px;
      padding: 6px 12px;
    }
  }
}
</style> 